const http = require('http');
const url = require('url');
const path = require('path');
const fs = require('fs');
const util = require('util');
const querystring = require('querystring');

function search(req, res) {
	res.setHeader('Content-Type', 'text/html;charset=utf-8');
	var urlObj = url.parse(req.url, !0);
	if (!urlObj.query || !urlObj.query.number) {
		res.write('参数错误');
		res.end();
	} else {
		fs.readFile('./data.json', 'utf-8', (err, data) => {
			if (err) {
				res.write('没有找到员工。');
			} else {
				data = JSON.parse(data);
				var one = data.data.find((item) => item.number == urlObj.query.number);
				if (one) {
					res.write(`找到员工：员工编号：${one.number}, 员工姓名：${one.name}，员工性别：${one.sex}，员工职位：${one.job}`)
				} else {
					res.write('没有找到员工。');
				}
			}
			res.end();
		})
	}
}

function create(req, res) {
	res.setHeader('Content-Type', 'text/html;charset=utf-8');
	var urlObj = url.parse(req.url, !0);
	req.setEncoding('utf8');
	let data = '';

	req.on('data', (chunk) => {
		data += chunk;
	});

	req.on('end', () => {
		data = querystring.parse(data);
		if (data.number && data.name && data.sex && data.job) {
			res.end(`员工：${data.name}信息保存成功`);
		} else {
			// TODO: 获取POST表单数据并保存到数据库

			// 提示保存成功
			res.end('参数错误，员工信息填写不全');
		}
	});
}

http.createServer((req, res) => {
	console.log(req.method + '  ' + req.url + '   ' + Date.now());
	if (req.method === 'GET') {
		if (req.url.indexOf('/server')  > -1) {
			search(req, res);
		} else {
			var fileName = '.' + req.url;
			if (req.url === '/') {
				fileName += 'jquery.html';
			}
			fs.readFile(fileName, (err, data) => {
				if (err) {
					console.log(err);
					res.writeHead(404);
					res.end();
				} else {
					res.writeHead(200);
					res.write(data, 'binary');
					res.end();
				}
			});
		}
	} else if (req.method === 'POST') {
		create(req, res);
	}
	console.log('\n');
}).listen(30000);
